<template>
  <view class="address">
    <!-- 导航栏 -->
    <NavBar title="收货地址" />

    <!-- 空地址提示 -->
    <nut-empty v-if="!loading && addressList.length === 0" description="暂无收货地址" image="empty">
      <template #footer>
        <nut-button type="primary" size="small" @click="addAddress">添加地址</nut-button>
      </template>
    </nut-empty>

    <!-- 加载中 -->
    <view v-if="loading" class="loading-container">
      <nut-indicator />
      <text>加载中...</text>
    </view>

    <!-- 地址列表 -->
    <view v-else-if="addressList.length > 0" class="address-list">
      <nut-swipe
        v-for="(item, index) in addressList"
        :key="item.id"  <!-- Use item.id as key -->
        @click="selectAddress(item)"
      >
        <view class="address-item">
          <view class="address-info">
            <view class="user-info">
              <text class="name">{{ item.name }}</text>
              <text class="phone">{{ item.phone }}</text>
              <nut-tag type="primary" v-if="item.isDefault">默认</nut-tag>
            </view>
            <view class="address-detail">
              {{ formatAddress(item) }}
            </view>
          </view>
          <view class="address-actions">
            <view class="action-item" @click.stop="editAddress(item)">
              <Edit size="16" />
              <text>编辑</text>
            </view>
          </view>
        </view>
        <template #right>
          <nut-button
            type="danger"
            square
            @click.stop="deleteAddress(item.id, index)" <!-- Pass id and index -->
          >
            删除
          </nut-button>
        </template>
      </nut-swipe>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-button" v-if="!loading">
      <nut-button type="primary" block @click="addAddress">新增收货地址</nut-button>
    </view>

    <!-- 地址表单弹窗 -->
    <nut-popup position="bottom" v-model:visible="showAddressForm" :style="{ height: '90%' }" round>
      <view class="address-form">
        <view class="form-header">
          <text class="title">{{ isEdit ? '编辑地址' : '新增地址' }}</text>
          <Close @click="cancelForm" />
        </view>
        <view class="form-content">
          <nut-form ref="formRef">
            <nut-form-item label="收货人" required :rules="[{ required: true, message: '请输入收货人姓名' }]">
              <nut-input v-model="addressForm.name" placeholder="请输入收货人姓名" />
            </nut-form-item>
            <nut-form-item label="手机号码" required :rules="[{ required: true, message: '请输入手机号码' }, { validator: 'phone', message: '手机号码格式不正确' }]">
              <nut-input v-model="addressForm.phone" placeholder="请输入手机号码" type="tel" />
            </nut-form-item>
            <nut-form-item label="所在地区" required :rules="[{ required: true, message: '请选择所在地区' }]">
              <nut-cell @click="showAreaPicker = true">
                <template #desc>
                  <view class="area-value" :class="{ 'placeholder': !addressForm.province }">
                    {{ addressForm.province && addressForm.city ?
                      `${addressForm.province} ${addressForm.city} ${addressForm.district || ''}` :
                      '请选择所在地区' }}
                  </view>
                </template>
              </nut-cell>
            </nut-form-item>
            <nut-form-item label="详细地址" required :rules="[{ required: true, message: '请输入详细地址' }]">
              <nut-textarea
                v-model="addressForm.addressDetail"
                placeholder="请输入详细地址信息，如街道、门牌号等"
                :max-length="100"
                limit-show
              />
            </nut-form-item>
            <nut-form-item label="设为默认地址">
              <nut-switch v-model="addressForm.isDefault" />
            </nut-form-item>
          </nut-form>
        </view>
        <view class="form-footer">
          <nut-button type="primary" block @click="saveAddress" :loading="saving">保存</nut-button>
        </view>
      </view>
    </nut-popup>

    <!-- 地区选择器 -->
    <nut-cascader
      v-model:visible="showAreaPicker"
      v-model="areaValue"
      title="选择地区"
      :options="areaOptions" 
      @change="onAreaChange"
      @path-change="onAreaPathChange"
      lazy
      :lazy-load="lazyLoadArea"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import Taro from '@tarojs/taro'
import { Edit, Close } from '@nutui/icons-vue-taro'
import { useLoading } from '../../hooks/useLoading'

// 获取路由参数
const router = Taro.getCurrentInstance().router
const fromOrder = router?.params?.from === 'order'

// 加载状态
const { loading, startLoading, endLoading } = useLoading(true)
const saving = ref(false)

// 地址列表
const addressList = ref<AddressItem[]>([])

// 地址表单
const showAddressForm = ref(false)
const isEdit = ref(false)
const formRef = ref<any>(null) // 表单引用
const addressForm = reactive<Partial<AddressItem>>({
  id: undefined,
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  addressDetail: '',
  isDefault: false
})

// 地区选择器
const showAreaPicker = ref(false)
const areaValue = ref([])
const areaOptions = ref([
  // 初始加载省份
])

// 模拟异步加载地区数据
const lazyLoadArea = (node, resolve) => {
  // 实际项目中应从 API 获取
  setTimeout(() => {
    if (node.root) {
      // 加载省份
      resolve([
        { value: '110000', text: '北京市', leaf: false },
        { value: '310000', text: '上海市', leaf: false },
        { value: '440000', text: '广东省', leaf: false },
        // ...更多省份
      ])
    } else if (node.level === 1) {
      // 加载城市
      if (node.value === '110000') {
        resolve([{ value: '110100', text: '北京市', leaf: false }])
      } else if (node.value === '310000') {
        resolve([{ value: '310100', text: '上海市', leaf: false }])
      } else if (node.value === '440000') {
        resolve([
          { value: '440100', text: '广州市', leaf: false },
          { value: '440300', text: '深圳市', leaf: false },
        ])
      } else {
        resolve([])
      }
    } else if (node.level === 2) {
      // 加载区县
      if (node.value === '110100') {
        resolve([
          { value: '110101', text: '东城区', leaf: true },
          { value: '110102', text: '西城区', leaf: true },
          { value: '110105', text: '朝阳区', leaf: true },
          { value: '110108', text: '海淀区', leaf: true },
        ])
      } else if (node.value === '310100') {
        resolve([
          { value: '310101', text: '黄浦区', leaf: true },
          { value: '310104', text: '徐汇区', leaf: true },
        ])
      } else if (node.value === '440100') {
        resolve([
          { value: '440103', text: '荔湾区', leaf: true },
          { value: '440104', text: '越秀区', leaf: true },
        ])
      } else if (node.value === '440300') {
        resolve([
          { value: '440303', text: '罗湖区', leaf: true },
          { value: '440304', text: '福田区', leaf: true },
        ])
      } else {
        resolve([])
      }
    }
  }, 500)
}

// 地区选择变化
const onAreaChange = (value) => {
  console.log('Area changed:', value)
}

// 地区路径变化 (用于更新表单)
const onAreaPathChange = (nodes) => {
  if (nodes.length >= 1) addressForm.province = nodes[0].text
  if (nodes.length >= 2) addressForm.city = nodes[1].text
  if (nodes.length >= 3) addressForm.district = nodes[2].text
}

// 格式化地址
const formatAddress = (address: AddressItem) => {
  return `${address.province || ''} ${address.city || ''} ${address.district || ''} ${address.addressDetail || ''}`.trim()
}

// 获取地址列表
const fetchAddressList = async () => {
  startLoading()
  try {
    const res = await userApi.getAddressList()
    addressList.value = res.data || []
  } catch (error) {
    console.error('获取地址列表失败:', error)
    Taro.showToast({ title: '加载地址失败', icon: 'none' })
  } finally {
    endLoading()
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(addressForm, {
    id: undefined,
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    addressDetail: '',
    isDefault: false
  })
  areaValue.value = [] // 清空地区选择器的值
  formRef.value?.reset()
}

// 添加地址
const addAddress = () => {
  isEdit.value = false
  resetForm()
  showAddressForm.value = true
}

// 编辑地址
const editAddress = (address: AddressItem) => {
  isEdit.value = true
  // 深拷贝一份数据到表单，避免直接修改列表中的对象
  Object.assign(addressForm, JSON.parse(JSON.stringify(address)))
  // 设置地区选择器的初始值 (需要根据实际数据结构调整 value)
  // 假设 API 返回的是名称，需要找到对应的 value
  // areaValue.value = [address.provinceValue, address.cityValue, address.districtValue]
  showAddressForm.value = true
}

// 删除地址
const deleteAddress = (id: string | number, index: number) => {
  Taro.showModal({
    title: '提示',
    content: '确定要删除该收货地址吗？',
    success: async (res) => {
      if (res.confirm) {
        Taro.showLoading({ title: '删除中...' })
        try {
          await userApi.deleteAddress(id)
          addressList.value.splice(index, 1)
          Taro.hideLoading()
          Taro.showToast({
            title: '删除成功',
            icon: 'success'
          })
        } catch (error) {
          Taro.hideLoading()
          console.error('删除地址失败:', error)
          Taro.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 保存地址
const saveAddress = async () => {
  try {
    await formRef.value.validate()
    saving.value = true
    Taro.showLoading({ title: '保存中...' })

    const params = {
      name: addressForm.name,
      phone: addressForm.phone,
      province: addressForm.province,
      city: addressForm.city,
      district: addressForm.district,
      detail: addressForm.addressDetail, // 注意字段映射
      isDefault: addressForm.isDefault
    }

    try {
      if (isEdit.value && addressForm.id) {
        // 更新地址
        await userApi.updateAddress(addressForm.id, params)
      } else {
        // 新增地址
        await userApi.addAddress(params)
      }

      // 如果设为默认，单独调用设置默认接口 (如果 add/update 不处理默认逻辑)
      // if (addressForm.isDefault && addressForm.id) {
      //   await userApi.setDefaultAddress(addressForm.id)
      // }

      Taro.hideLoading()
      Taro.showToast({
        title: '保存成功',
        icon: 'success'
      })
      showAddressForm.value = false
      fetchAddressList() // 刷新列表
    } catch (apiError) {
      Taro.hideLoading()
      console.error('保存地址失败:', apiError)
      Taro.showToast({ title: `保存失败: ${apiError.message || ''}`, icon: 'none' })
    }
  } catch (validationError) {
    console.log('表单校验失败:', validationError)
    // 校验失败，nutui 会自动提示
  } finally {
    saving.value = false
  }
}

// 取消表单
const cancelForm = () => {
  showAddressForm.value = false
}

// 选择地址
const selectAddress = async (address: AddressItem) => {
  if (fromOrder) {
    // 如果是从订单页过来，设置默认地址并返回
    if (!address.isDefault) {
      Taro.showLoading({ title: '设置中...' })
      try {
        await userApi.setDefaultAddress(address.id)
        // 更新本地列表状态，避免重新请求
        addressList.value.forEach(item => item.isDefault = item.id === address.id)
        Taro.hideLoading()
      } catch (error) {
        Taro.hideLoading()
        console.error('设置默认地址失败:', error)
        Taro.showToast({ title: '设置默认地址失败', icon: 'none' })
        return // 设置失败则不返回
      }
    }
    // 将选中的地址信息存入缓存或通过事件总线传递给上一个页面
    Taro.setStorageSync('selectedAddress', address)
    Taro.navigateBack()
  } else {
    // 否则，可以跳转到编辑页面或执行其他操作
    // editAddress(address)
  }
}

// 页面加载时获取地址列表
onMounted(() => {
  fetchAddressList()
})

</script>

<style lang="scss">
.address {
  padding-bottom: calc(env(safe-area-inset-bottom) + 80px); // 留出底部按钮空间
  background-color: #f7f8fa;
  min-height: 100vh;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 100px;
  color: #999;
  font-size: 14px;

  nut-loading {
    margin-bottom: 10px;
  }
}

.address-list {
  padding: 10px;

  .nut-swipe {
    margin-bottom: 10px;
    border-radius: 8px;
    overflow: hidden; // 确保圆角生效
  }

  .address-item {
    display: flex;
    align-items: center;
    padding: 15px;
    background-color: #fff;
    // border-radius: 8px; // 移到 nut-swipe 上

    .address-info {
      flex: 1;
      margin-right: 15px;

      .user-info {
        display: flex;
        align-items: center;
        margin-bottom: 5px;

        .name {
          font-size: 16px;
          font-weight: bold;
          margin-right: 10px;
        }

        .phone {
          font-size: 14px;
          color: #666;
          margin-right: 10px;
        }

        .nut-tag {
          margin-left: auto; // 将标签推到右侧
        }
      }

      .address-detail {
        font-size: 14px;
        color: #333;
        line-height: 1.5;
      }
    }

    .address-actions {
      .action-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        color: #999;
        font-size: 12px;

        .nut-icon {
          margin-bottom: 2px;
        }
      }
    }
  }
}

.bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 15px;
  padding-bottom: calc(env(safe-area-inset-bottom) + 10px);
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
}

.address-form {
  display: flex;
  flex-direction: column;
  height: 100%;

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;

    .title {
      font-size: 16px;
      font-weight: bold;
    }

    .nut-icon {
      color: #999;
      cursor: pointer;
    }
  }

  .form-content {
    flex: 1;
    overflow-y: auto;
    padding: 10px 0;

    .nut-cell {
      padding-right: 0; // 移除右侧内边距以对齐
    }

    .area-value {
      flex: 1;
      text-align: right;
      color: #333;
      &.placeholder {
        color: #999;
      }
    }

    .nut-textarea {
      padding: 10px;
      border: 1px solid #f0f0f0;
      border-radius: 4px;
    }
  }

  .form-footer {
    padding: 10px 15px;
    border-top: 1px solid #f0f0f0;
  }
}

// 地区选择器样式调整
.nut-cascader {
  .nut-cascader__bar {
    padding: 10px 15px;
  }
}
</style>